package com.house.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenKit {
    public static final String ISSUER = "house.com";

    public static String createToken(Map<String, String> payload, int validTime) throws Exception {
        Date issuedAt = new Date();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        JWTCreator.Builder tokenBuilder = JWT.create().withIssuer(ISSUER).withIssuedAt(issuedAt).withExpiresAt(TokenKit.addTime(issuedAt, validTime, Calendar.SECOND));//Token过期时间
        tokenBuilder.withHeader(map);
        payload.forEach(tokenBuilder::withClaim);
        Algorithm algorithm = Algorithm.RSA256((RSAPublicKey) RSAKit.getPublicKey(RSAKit.getTokenPublicKey()), (RSAPrivateKey) RSAKit.getPrivateKey(RSAKit.getTokenPrivateKey()));
        String token = tokenBuilder.sign(algorithm);
        return token;
    }

    public static Map<String, Claim> verifyToken(String token) throws Exception {
        Algorithm algorithm = Algorithm.RSA256((RSAPublicKey) RSAKit.getPublicKey(RSAKit.getTokenPublicKey()), (RSAPrivateKey) RSAKit.getPrivateKey(RSAKit.getTokenPrivateKey()));
        JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
        DecodedJWT jwt = verifier.verify(token);
        Map<String, Claim> claims = jwt.getClaims();
        return claims;
    }

    private static boolean compareLongTime(long time,long exp) {
        long now = System.currentTimeMillis();
        long cycle = exp * 1000;
        if (now > (time + cycle)) {
            return false;
        } else {
            return true;
        }
    }

    private static Date addTime(Date startDateTime, int interval, int calendar) {
        Calendar todayCalendar = Calendar.getInstance();
        todayCalendar.setTime(startDateTime);
        todayCalendar.add(calendar, interval);
        Date currentTime = todayCalendar.getTime();
        return currentTime;
    }

}
